package com.fc.advbox.controller.admin;

import com.fc.advbox.entity.AdvUserEntity;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.RRException;
import com.fc.advbox.utils.ShiroUtils;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * BaserController
 */
public class BaseController {

	protected AdvUserEntity getUser() {
		return ShiroUtils.getUserEntity();
	}

	protected Long getUserId() {
		if(getUser() == null)
		{
			throw new RRException("用户未登录, 请重新登陆");
		}
		return getUser().getId();
	}

	protected Map<String, Object> calculatePagination(Map<String, Object> params) {
		if(params == null)
		{
			params = Maps.newHashMap();
		}

        if(params.get(Constant.DEFAULT_LIMIT_NAME) == null)
		{
			params.put(Constant.DEFAULT_LIMIT_NAME, Constant.DEFAULT_LIMIT);
		}
		else
		{
			params.put(Constant.DEFAULT_LIMIT_NAME, Integer.valueOf(String.valueOf(params.get(Constant.DEFAULT_LIMIT_NAME))));
		}

        if(params.get(Constant.DEFAULT_PAGE_NAME) == null)
        {
            params.put(Constant.DEFAULT_PAGE_NAME, Constant.DEFAULT_PAGE);
        }

		int limit = (int)params.putIfAbsent(Constant.DEFAULT_LIMIT_NAME, Constant.DEFAULT_LIMIT);
		int page = Integer.valueOf(String.valueOf(params.putIfAbsent(Constant.DEFAULT_PAGE_NAME, Constant.DEFAULT_PAGE)));
		params.put(Constant.DEFAULT_OFFSET_NAME, (page - 1) * limit);
		return params;
	}

	protected int calculateOffset(Integer offset, Integer limit)
	{
		if(offset == null)
		{
			offset = Constant.DEFAULT_OFFSET;
		}
		if(limit == null)
		{
			limit = Constant.DEFAULT_LIMIT;
		}
		return offset * limit;
	}
}
